package com.wutuo.aggragation;

import cn.apestar.core.framework.AbstractAppConfig;
import cn.apestar.core.framework.datasource.ManagedDataSource;
import cn.apestar.core.framework.settings.MobileAPIModuleSettings;
import cn.apestar.core.framework.spring.PropertyContext;
import cn.apestar.sms.provider.conf.YunPianConfig;
import com.mysql.jdbc.Driver;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 标题、简要说明. <br>
 * 类详细说明.
 * <p/>
 * Copyright: Copyright (c) 2016年05月28日 16:29
 * <p/>
 * Company: AAAA
 * <p/>
 * @author Kent
 * @version 1.0.0
 */
@Configuration
@ComponentScan(basePackages = {"com.wutuo" , "cn.apestar"})
@EnableAspectJAutoProxy
@EnableTransactionManagement(proxyTargetClass = true)
public class AppConfig extends AbstractAppConfig {

    @Autowired
    Environment environment;

    @Override
    public MobileAPIModuleSettings moduleSettings() {
        MobileAPIModuleSettings mobileAPIModuleSetting = new MobileAPIModuleSettings();
        mobileAPIModuleSetting.setEnvironment(environment.getRequiredProperty("environment"));
        mobileAPIModuleSetting.setSecretKey(environment.getRequiredProperty("secretKey"));
        mobileAPIModuleSetting.setModuleName("TMonk");
        return mobileAPIModuleSetting;
    }

    @Bean
    public DataSource siteDataSource() {
        ManagedDataSource dataSource = new ManagedDataSource();
        dataSource.setDriverClassName(Driver.class.getName());
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        dataSource.setMaxActive(environment.getRequiredProperty("jdbc.max.active", Integer.class));
        dataSource.setDefaultAutoCommit(false);
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean siteSqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        sqlSessionFactoryBean.setDataSource(siteDataSource());
        sqlSessionFactoryBean.setPlugins(new Interceptor[] {paginationInterceptor()});

        Properties properties = new Properties();
        properties.setProperty("mapUnderscoreToCamelCase", Boolean.TRUE.toString());
        sqlSessionFactoryBean.setConfigurationProperties(properties);

        return sqlSessionFactoryBean;
    }

    @Bean(name = "siteTransactionManager")
    public PlatformTransactionManager siteTransactionManager() {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(siteDataSource());
        return dataSourceTransactionManager;
    }

    @Override
    public void configureEnvironment() throws IOException {
        ConfigurableEnvironment temp = (ConfigurableEnvironment) environment;
        PropertyContext propertySource = new PropertyContext();
        Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath*:*.properties");
        resources = processResource(resources);
        propertySource.setLocations(resources);
        propertySource.loadAllProperties();
        temp.getPropertySources().addLast(new PropertiesPropertySource("properties", propertySource.getAllProperties()));
    }

    private Resource[] processResource(Resource[] resources) throws IOException {
        List<Resource> result = new ArrayList<>();
        for (Resource resource : resources) {
            URI uri = resource.getURI();
            if ("jar".equals(uri.getScheme()) && uri.toString().endsWith("jdbc.properties")) {
                // exclude this file
            } else if ("jar".equals(uri.getScheme()) && uri.toString().endsWith("test.properties")) {
                // exclude this file
            } else {
                result.add(resource);
            }
        }
        return result.toArray(new Resource[result.size()]);
    }

    @Bean public YunPianConfig yunPianConfig() {
        YunPianConfig smsConfig = new YunPianConfig();
        smsConfig.setAccount(environment.getRequiredProperty("yp.account"));
        smsConfig.setPassword(environment.getRequiredProperty("yp.passwd"));
        smsConfig.setBaseUrl(environment.getRequiredProperty("yp.url"));
        smsConfig.setApiKey(environment.getRequiredProperty("yp.apikey"));
        return smsConfig;
    }
}
